package io.renren.modules.store.controller;

import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.renren.common.annotation.NoRepeatSubmit;
import io.renren.common.exception.RRException;
import io.renren.common.utils.*;
import io.renren.modules.store.entity.TStoreFoodFlavorEntity;
import io.renren.modules.store.entity.TStoreFoodSpecsEntity;
import io.renren.modules.store.entity.TStoreFoodTypeEntity;
import io.renren.modules.store.service.TStoreFoodFlavorService;
import io.renren.modules.store.service.TStoreFoodSpecsService;
import io.renren.modules.store.service.TStoreFoodTypeService;
import io.renren.modules.sys.controller.AbstractController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import io.renren.modules.store.entity.TStoreFoodEntity;
import io.renren.modules.store.service.TStoreFoodService;


/**
 * @author steakliu
 * @email 2319492349@qq.com
 * @date 2021-01-24 17:20:11
 */
@RestController
@RequestMapping("store/tstorefood")
public class TStoreFoodController extends AbstractController {
    @Autowired
    private TStoreFoodService tStoreFoodService;
    @Autowired
    private TStoreFoodTypeService tStoreFoodTypeService;
    @Autowired
    private TStoreFoodFlavorService storeFoodFlavorService;
    @Autowired
    private TStoreFoodSpecsService storeFoodSpecsService;

    /**
     * 沽清
     *
     * @param id
     * @param status
     * @param batch  0根据id沽清 1沽清全部
     * @return
     */
    @RequestMapping("/sellOff")
    public R sellOff(@RequestParam(required = false) String id, @RequestParam Integer status, @RequestParam Integer batch) {
        tStoreFoodService.update(new LambdaUpdateWrapper<TStoreFoodEntity>()
                .set(TStoreFoodEntity::getSellOffStatus, status)
                .eq(batch == 0, TStoreFoodEntity::getId, id)
                .eq(batch == 1, TStoreFoodEntity::getSellerId, getSeller())
        );
        return R.ok();
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("store:tstorefood:list")
    public R list(@RequestParam Map<String, Object> params) {
        params.put("sellerId", getSeller());
        params.put("key", params.get("key"));
        params.put("typeId", params.get("typeId"));
        PageUtils page = tStoreFoodService.queryPage(params);

        return R.ok().put("page", page);
    }

    @RequestMapping("/stopOrStartFood")
    @RequiresPermissions("store:tstorefood:stopOrStartFood")
    public R stopOrStartFood(@RequestParam Long id, @RequestParam Integer status) {
        tStoreFoodService.update(new UpdateWrapper<TStoreFoodEntity>()
                .eq("seller_id", getSeller())
                .eq("id", id)
                .set("status", status)
        );
        return R.ok();
    }

    /**
     * 点菜展示列表
     */
    @RequestMapping("/listFoodShow")
    @RequiresPermissions("store:tstorefood:list")
    public R listFoodShow(@RequestParam Map<String, Object> params) {
        params.put("sellerId", getSeller());
        PageUtils page = tStoreFoodService.queryListFoodPage(params);
        return R.ok().put("page", page);
    }

    /**
     * 根据菜品助词码获取菜品
     */
    @RequestMapping("/getFoodListByShortCode")
    @RequiresPermissions("store:tstorefood:list")
    public R getFoodListByShortCode(@RequestParam Map<String, Object> params) {
        params.put("sellerId", getSeller());
        List<TStoreFoodEntity> list = tStoreFoodService.list(new QueryWrapper<TStoreFoodEntity>()
                .like("short_code", params.get("shortCode"))
                .eq("seller_id", getSeller()));
        return R.ok().put("page", list);
    }

    /**
     * 菜品树
     */
    @GetMapping("/listFood")
    @RequiresPermissions("store:tstorefood:listFood")
    public R listFood() {
        //查出租户下的所有菜品类型
        QueryWrapper<TStoreFoodTypeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(getSeller() != null, "seller_id", getSeller())
                .eq("status", 1);
        List<TStoreFoodTypeEntity> list = tStoreFoodTypeService.list(queryWrapper);
        List<Map<String, Object>> foodEntities = new ArrayList<>();
        //TODO 折扣方案目前只设置在了菜品类型上面，没有设置在菜品上面
        if (list.size() != 0) {
            for (TStoreFoodTypeEntity ts : list) {
                Map<String, Object> foodMap = new HashMap<>();
                QueryWrapper<TStoreFoodEntity> foodQuery = new QueryWrapper<>();
                foodQuery.eq("type_id", ts.getId());
                foodQuery.eq("status", 1);
                //TODO 这里应该加上菜品是否允许折扣的条件
                List<TStoreFoodEntity> foodList = tStoreFoodService.list(foodQuery);
                if (foodList.size() > 0) {
                    foodMap.put("foodTypeName", ts.getClassificationName());
                    foodMap.put("foodList", foodList);
                    foodEntities.add(foodMap);
                }
            }
            return R.ok().put("foodList", foodEntities);
        } else {
            return R.ok().put("foodList", null);
        }

    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("store:tstorefood:info")
    public R info(@PathVariable("id") Long id) {
        TStoreFoodEntity tStoreFood = tStoreFoodService.getById(id);
        String useRange = tStoreFood.getUseRange();
        List<Long> longs = ReplaceUtil.strToList(useRange);
        tStoreFood.setUseRangeList(longs);
        List<TStoreFoodSpecsEntity> specsEntityList = storeFoodSpecsService.list(new QueryWrapper<TStoreFoodSpecsEntity>()
                .eq("food_id", tStoreFood.getId())
        );
        List<TStoreFoodFlavorEntity> flavorEntityList = storeFoodFlavorService.list(new QueryWrapper<TStoreFoodFlavorEntity>()
                .eq("food_id", tStoreFood.getId())
        );
        tStoreFood.setSpecsList(specsEntityList);
        tStoreFood.setFlavorList(flavorEntityList);
        return R.ok().put("tStoreFood", tStoreFood);
    }

    /**
     * 保存
     */
    @NoRepeatSubmit
    @RequestMapping("/save")
    @RequiresPermissions("store:tstorefood:save")
    @Transactional(rollbackFor = Exception.class)
    public R save(@RequestBody TStoreFoodEntity tStoreFood) {
        TStoreFoodEntity one = tStoreFoodService.getOne(new QueryWrapper<TStoreFoodEntity>()
                .eq("seller_id", getSeller())
                .eq("food_name", tStoreFood.getFoodName())
                .eq("type_id", tStoreFood.getTypeId())
        );
        if (!BeanJudgeUtil.beanIsNull(one)) {
            throw new RRException("同菜品类型下已存在同名菜品，请勿重复添加");
        }
        tStoreFood.setFoodNo(FastIDUtil.fastId());
        tStoreFood.setSellerId(getSeller());
        tStoreFood.setUseRange(ReplaceUtil.replaceZKH(tStoreFood.getUseRangeList().toString()));
        tStoreFoodService.save(tStoreFood);

        TStoreFoodEntity foodEntity = tStoreFoodService.getOne(new QueryWrapper<TStoreFoodEntity>()
                .eq("seller_id", getSeller())
                .eq("food_no", tStoreFood.getFoodNo())
        );
        //使用多口味
        if (tStoreFood.getFlavorStatus() == 1) {
            List<TStoreFoodFlavorEntity> list = new ArrayList<>();
            tStoreFood.getFlavorList().forEach(item -> {
                TStoreFoodFlavorEntity flavorEntity = new TStoreFoodFlavorEntity();
                flavorEntity.setFlavorId(FastIDUtil.fastId());
                flavorEntity.setFlavorName(item.getFlavorName());
                flavorEntity.setFoodId(foodEntity.getId());
                list.add(flavorEntity);
            });
            storeFoodFlavorService.saveBatch(list);
        }
        //使用多规格
        if (tStoreFood.getNormsStatus() == 1) {
            List<TStoreFoodSpecsEntity> list = new ArrayList<>();
            tStoreFood.getSpecsList().forEach(item -> {
                TStoreFoodSpecsEntity specsEntity = new TStoreFoodSpecsEntity();
                specsEntity.setSpecsId(FastIDUtil.fastId());
                specsEntity.setFoodId(foodEntity.getId());
                specsEntity.setCostPrice(item.getCostPrice());
                specsEntity.setPrice(item.getPrice());
                specsEntity.setSpecsName(item.getSpecsName());
                list.add(specsEntity);
            });
            storeFoodSpecsService.saveBatch(list);
        }
        return R.ok();
    }

    /**
     * 修改使用范围
     */
    @RequestMapping("/updateUseRange")
    @RequiresPermissions("store:tstorefood:update")
    public R updateUseRange(@RequestBody TStoreFoodEntity foodEntity) {
        foodEntity.setUseRange(ReplaceUtil.replaceZKH(foodEntity.getUseRangeList().toString()));
        tStoreFoodService.updateById(foodEntity);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("store:tstorefood:update")
    @Transactional(rollbackFor = Exception.class)
    public R update(@RequestBody TStoreFoodEntity tStoreFood) {
        tStoreFoodService.updateById(tStoreFood);
        if (tStoreFood.getFlavorStatus() == 1) {
            if (tStoreFood.getFlavorList().size() > 0) {
                List<TStoreFoodFlavorEntity> list = new ArrayList<>();
                tStoreFood.getFlavorList().forEach(item -> {
                    TStoreFoodFlavorEntity flavorEntity = new TStoreFoodFlavorEntity();
                    flavorEntity.setId(item.getId());
                    list.add(flavorEntity);
                });
                storeFoodFlavorService.saveOrUpdateBatch(list);
            }
        } else {
            if (tStoreFood.getFlavorList().size() > 0) {
                storeFoodFlavorService.remove(new QueryWrapper<TStoreFoodFlavorEntity>()
                        .eq("food_id", tStoreFood.getId())
                );
            }
        }

        if (tStoreFood.getNormsStatus() == 1) {
            if (tStoreFood.getSpecsList().size() > 0) {
                List<TStoreFoodSpecsEntity> list1 = new ArrayList<>();
                tStoreFood.getSpecsList().forEach(item -> {
                    TStoreFoodSpecsEntity specsEntity = new TStoreFoodSpecsEntity();
                    specsEntity.setId(item.getId());
                    list1.add(specsEntity);
                });
                storeFoodSpecsService.saveOrUpdateBatch(list1);
            }
        } else {
            if (tStoreFood.getSpecsList().size() > 0) {
                storeFoodSpecsService.remove(new QueryWrapper<TStoreFoodSpecsEntity>()
                        .eq("food_id", tStoreFood.getId())
                );
            }
        }
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("store:tstorefood:delete")
    public R delete(@RequestBody Long[] ids) {
        tStoreFoodService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
